/********************************************************************
	created:	2012/02/26   23:11
	filename: 	hy_scope_locker.h
	author:		supercaco@sina.com
	purpose:	
*********************************************************************/
#ifndef _HY_SCOPE_LOCKER_H_
#define _HY_SCOPE_LOCKER_H_

// Helper class to lock and unlock a mutex automatically.
template <typename Mutex>
class hy_scoped_lock
	//: private zr_noncopyable
{
public:
	// Constructor acquires the lock.
	hy_scoped_lock(Mutex& m)
		: mutex_(m)
	{
		mutex_.lock();
		locked_ = true;
	}

	// Destructor releases the lock.
	~hy_scoped_lock()
	{
		if (locked_)
			mutex_.unlock();
	}

	// Explicitly acquire the lock.
	void lock()
	{
		if (!locked_)
		{
			mutex_.lock();
			locked_ = true;
		}
	}

	// Explicitly release the lock.
	void unlock()
	{
		if (locked_)
		{
			mutex_.unlock();
			locked_ = false;
		}
	}

	// Test whether the lock is held.
	bool locked() const
	{
		return locked_;
	}

	// Get the underlying mutex.
	Mutex& mutex()
	{
		return mutex_;
	}

private:
	// The underlying mutex.
	Mutex& mutex_;

	// Whether the mutex is currently locked or unlocked.
	bool locked_;
};

typedef hy_scoped_lock<hy_mutex> hy_lock;

#endif  //_HY_SCOPE_LOCKER_H_
